using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using IGlobalist.Cms.Common;
using IGlobalist.Cms.Bll;
using IGlobalist.Cms.Model;
using IGlobalist.Cms.Presentation;
using System.Text.RegularExpressions;
using System.IO;

namespace IGlobalist.Cms
{
    public partial class ForumManagement : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            #region addforum
                if (Request["addForum"] == "1")
                {
                    ViewState["Forum_Name"]= Request["txtforumName"];

                    ViewState["Forum_Description"]=Request["txtforumDescription"];

                    ViewState["Forum_Status"]=Request["ddlForumStatus"];

                    long parentID = 0;

                    long templateId = Convert.ToInt64(Request["template"]);

                    long id = Convert.ToInt64(Request["ID"]);

                    SaveForum(templateId,id, parentID);

                    long pid = Convert.ToInt64(Request["pageID"]);


                    string path = pid + "_0_0/default.aspx?forum=1";
                    Response.Redirect(path);
                }
            #endregion

            #region addThread
                if (Request["addThread"] == "1")
                {
                    ViewState["Thread_Name"] =""+  Request["txtThreadName"];

                    ViewState["Thread_Description"] = ""+ Request["txtThreadDescription"];

                    long id = 0;
                    long forumId = Convert.ToInt64(Request["ddlForumt"]);
                    
                    SaveThread(forumId, id);

                    long pid = Convert.ToInt64(Request["pageID"]);
                    string path = pid + "_0_0/default.aspx";
                    Response.Redirect(path);
                }
            #endregion

            #region topic
                 if (Request["addTopic"] == "1")
                {
                    ViewState["Topic_Name"] = Request["txtTopicName"];

                    ViewState["Topic_Description"] = Request["txtTopicDescription"];

                    long threadId=Convert.ToInt64(Request["threadID"]);

                    long id = 0;

                    SaveTopic(id, threadId);

                    long pid = Convert.ToInt64(Request["pageID"]);
                    string path = pid + "_" + threadId + "_0/default.aspx";
                    Response.Redirect(path);
                }
            #endregion

            #region SaveReply
                if (Request["saveReply"] == "1")
                {
                    ViewState["Quote_Name"] = Request["txtQuoteName"];

                    ViewState["Quote_Description"] = Request["txtQuoteDescription"];

                    long contentId = Convert.ToInt64(Request["contentId"]);

                    long topicId = Convert.ToInt64(Request["topicId"]);

                    long id = 0;

                    SaveReply(contentId, id);

                    long pid = Convert.ToInt64(Request["pageID"]);
                    string path = pid + "_" + topicId + "_0/default.aspx";
                    Response.Redirect(path);
                }
          #endregion

            #region  addContent
            if (Request["addContent"] == "1")
            {
                ViewState["Content_Name"] = Request["txtContentName"];

                ViewState["Content_Description"] = Request["txtContentDescription"];

                long topicId = Convert.ToInt64(Request["topicId"]);

                long id = Convert.ToInt64(Request["contentId"]);

                long pid = Convert.ToInt64(Request["pageID"]);

                SaveContent(topicId, id, pid);

                string path = pid + "_" + topicId + "_0/default.aspx";
                Response.Redirect(path);
            }
            #endregion

            #region  editContent
            if (Request["editContent"] == "1")
            {
                ViewState["Content_Name"] = Request["txtContentName"];

                ViewState["Content_Description"] = Request["txtContentDescription"];

                long topicId = Convert.ToInt64(Request["topicId"]);

                long contentId = Convert.ToInt64(Request["contentId"]);
                long pid = Convert.ToInt64(Request["pageID"]);
               

                SaveContent(topicId, contentId,pid);

                string path = pid + "_" + topicId + "_0/default.aspx";
                Response.Redirect(path);
            }
            #endregion

            #region DeleteReply
            if (Request["dlecontent"] == "1")
            {
                long contentId = Convert.ToInt64(Request["contentId"]);

                DeleteContent(contentId);

                long pid = Convert.ToInt64(Request["pageID"]);
                long topicId = Convert.ToInt64(Request["topicId"]);
                string path = pid + "_" + topicId + "_0/default.aspx";
                Response.Redirect(path);
            }
            #endregion


            #region Permission

            if (Request["permission"] == "1")
            {
                long Id = Convert.ToInt64(Request["topicId"]);
                ViewState["Version"] = Request["value"];

                Permissions_Forum(Id);
                long pid = Convert.ToInt64(Request["pageID"]);
                long topicId = Convert.ToInt64(Request["topicId"]);
                string path;
                if(pid==topicId)
                    path = pid + "_0_0/default.aspx?forum=1";
                else
                    path = pid + "_" + topicId + "_0/default.aspx";
                Response.Redirect(path);
            }
            #endregion

            #region editThread

            if (Request["editThread"] == "1")
            {
                long Id = Convert.ToInt64(Request["topicId"]);
                ViewState["Version"] = Request["value"];

                Permissions_Forum(Id);

                long pid = Convert.ToInt64(Request["pageID"]);
                long topicId = Convert.ToInt64(Request["topicId"]);
                string path;
                
                path = pid + "_0_0/default.aspx?forum=1&editF=1";
                
                Response.Redirect(path);
            }
            #endregion
        }

        private void SaveForum(long templateId, long id, long parentID)
        {
            #region class
            ICmsClass clazzObject= new CmsClass();
              if (Session["ClassForumId"] != null)
              {
                  clazzObject = (CmsClass)Session["ClassForumId"];
              }
              else
              {
                  IList<ICmsClass> cList = ClassController.GetClassListByClassTypeID((short)CmsObjectType.Page,true);
                  foreach (ICmsClass clazz in cList)
                      for (int i = 0; i < clazz.PropertyList.Count; i++)
                          if ((Convert.ToString(clazz.PropertyList[i].Name) == "TypeClass") && (Convert.ToString(clazz.PropertyList[i].Value) == "Forum"))
                          {
                              clazzObject = clazz;
                              Session["ClassForumId"] = clazz;
                              break;
                          }
              }

            #endregion

            IPage forum =  new IGlobalist.Cms.Model.Page();
            if (id > 0)
            {
                forum = PageController.GetPage(id);
                forum.EditedBy = IGlobalistMembership.GetUser().ID;
                forum.EditedDate = DateTime.Now;
            }
            else
            {
                forum.Class = clazzObject;
                forum.ClassID = clazzObject.ID;
                forum.ClassTypeID = (short)CmsObjectType.Page;
                forum.CreatedDate = DateTime.Now;
                forum.Author = IGlobalistMembership.GetUser().ID;                
                forum.ParentID = parentID;
                forum.TemplateID = templateId;
            }
            
            forum.Description = ViewState["Forum_Description"].ToString();
            forum.Hidden = false;
            
            forum.Name = ViewState["Forum_Name"].ToString();
            forum.Order = 0;
            forum.Version = Convert.ToInt16(ViewState["Forum_Status"]);
            

            if (id > 0)
                PageController.UpdatePage(forum);
            else
                PageController.InsertPage(forum);
        }

        private void SaveTopic(long id, long threadId)
        {
             #region class
            ICmsClass clazzObject= new CmsClass();
              if (Session["ClassTopicId"] != null)
              {
                  clazzObject = (CmsClass)Session["ClassTopicId"];
              }
              else
              {
                  IList<ICmsClass> cList = ClassController.GetClassListByClassTypeID((short)CmsObjectType.ContentCategory,true);
                  foreach (ICmsClass clazz in cList)
                      for (int i = 0; i < clazz.PropertyList.Count; i++)
                          if ((Convert.ToString(clazz.PropertyList[i].Name) == "TypeClass") && (Convert.ToString(clazz.PropertyList[i].Value) == "Forum"))
                          {
                              clazzObject = clazz;
                              Session["ClassTopicId"] = clazz;
                              break;
                          }
              }

            #endregion

            IContentCategory topic = new Category();
            if (id > 0)
            {
                topic = CategoryController.GetCategory(id);
                topic.EditedBy = IGlobalistMembership.GetUser().ID;
                topic.EditedDate = DateTime.Now;
            }
            else
            {
                topic.Author = IGlobalistMembership.GetUser().ID;
                topic.Class = clazzObject;
                topic.ClassID = clazzObject.ID;
                topic.ClassTypeID = (short)CmsObjectType.ContentCategory;
                topic.CreatedDate = DateTime.Now;                
            }


            topic.Name = ViewState["Topic_Name"].ToString();
            topic.Description = ViewState["Topic_Description"].ToString(); 

            topic.Description = ViewState["Topic_Description"].ToString();
            topic.Name = ViewState["Topic_Name"].ToString(); 

            topic.Order = 0; // Request("order");
            topic.ParentID = threadId;
            if (id > 0)
                CategoryController.UpdateCategory(topic);
            else
                CategoryController.InsertCategory(topic);
        }

        private void SaveThread(long forumId, long id)
        {

            #region class
            ICmsClass clazzObject = new CmsClass();
            if (Session["ClassThreadId"] != null)
            {
                clazzObject = (CmsClass)Session["ClassThreadId"];
            }
            else
            {
                IList<ICmsClass> cList = ClassController.GetClassListByClassTypeID((short)CmsObjectType.ContentCategory,true);
                foreach (ICmsClass clazz in cList)
                    for (int i = 0; i < clazz.PropertyList.Count; i++)
                        if ((Convert.ToString(clazz.PropertyList[i].Name) == "TypeClass") && (Convert.ToString(clazz.PropertyList[i].Value) == "Forum"))
                        {
                            clazzObject = clazz;
                            Session["ClassThreadId"] = clazz;
                            break;
                        }
            }

            #endregion

            IPage forum = new IGlobalist.Cms.Model.Page(); ;
            forum = PageController.GetPage(forumId);
            IContentCategory theard = new Category();
            if (id > 0)
            {
                theard = CategoryController.GetCategory(id);
                theard.EditedBy = IGlobalistMembership.GetUser().ID;
                theard.EditedDate = DateTime.Now;
            }
            else
            {
                theard.Author = IGlobalistMembership.GetUser().ID;
                theard.Class = clazzObject;
                theard.ClassID = clazzObject.ID;
                theard.ClassTypeID = (short)CmsObjectType.ContentCategory;
                theard.CreatedDate = DateTime.Now;                

            }

            theard.Description = Convert.ToString(ViewState["Thread_Description"]);
            theard.Name = Convert.ToString(ViewState["Thread_Name"]);
            theard.Order = 0; // Request("order");
            if (id > 0)
                CategoryController.UpdateCategory(theard);
            else
            {                
                CategoryController.InsertCategory(theard);
                // ad vao page   
                forum = PageController.GetPageCurrent(forumId);
                ContentCategoryList listTheard = new ContentCategoryList();
                listTheard = forum.CategoryList;
                listTheard.Add(theard);
                forum.CategoryList = listTheard;

                PageController.UpdatePage(forum);
            }
        }

        private void SaveContent(long topicId, long id, long pid)
        {
             #region class
            ICmsClass clazzObject = new CmsClass();
            if (Session["ClassContentId"] != null)
            {
                clazzObject = (CmsClass)Session["ClassContentId"];
            }
            else
            {
                IList<ICmsClass> cList = ClassController.GetClassListByClassTypeID((short)CmsObjectType.Content,true);
                foreach (ICmsClass clazz in cList)
                    for (int i = 0; i < clazz.PropertyList.Count; i++)
                        if ((Convert.ToString(clazz.PropertyList[i].Name) == "TypeClass") && (Convert.ToString(clazz.PropertyList[i].Value) == "Forum"))
                        {
                            clazzObject = clazz;
                            Session["ClassContentId"] = clazz;
                            break;
                        }
            }

            #endregion

            IContent content =new IGlobalist.Cms.Model.Content();
            if (id > 0)
            {
                content = ContentController.GetContent(id);
                content.EditedBy = IGlobalistMembership.GetUser().ID;
                content.EditedDate = DateTime.Now;
            }
            else
            {
                content.Class = clazzObject;
                content.ClassID = clazzObject.ID;
                content.ClassTypeID = (short)CmsObjectType.Content;

                content.Author = IGlobalistMembership.GetUser().ID;
                content.CategoryID = topicId;
                content.PageID = pid;
                content.CreatedDate = DateTime.Now;
            }

            content.Description = Filter(ViewState["Content_Description"].ToString());
            content.Content = Filter(ViewState["Content_Description"].ToString());
            content.Name = ViewState["Content_Name"].ToString();
            content.Title = ViewState["Content_Name"].ToString();

            if (id > 0)
            {
                ContentController.UpdateContent(content);
            }
            else
                id = ContentController.InsertContent(content);

            UploadContentfile(content, id);

        }

        private void SaveReply(long contentId, long id)
        {

             #region class
            ICmsClass clazzObject = new CmsClass();
            if (Session["ClassNotetId"] != null)
            {
                clazzObject = (CmsClass)Session["ClassNotetId"];
            }
            else
            {
                IList<ICmsClass> cList = ClassController.GetClassListByClassTypeID((short)CmsObjectType.ContentNote,true);
                foreach (ICmsClass clazz in cList)
                    for (int i = 0; i < clazz.PropertyList.Count; i++)
                        if ((Convert.ToString(clazz.PropertyList[i].Name) == "TypeClass") && (Convert.ToString(clazz.PropertyList[i].Value) == "Forum"))
                        {
                            clazzObject = clazz;
                            Session["ClassNotetId"] = clazz;
                            break;
                        }
            }

            #endregion

            IContentNote note = new ContentNote();

            if (id > 0)
            {
                note = ContentNodeController.GetContentNote(id);
                note.EditedBy = IGlobalistMembership.GetUser().ID;
                note.EditedDate = DateTime.Now;
                note.ActionType = ActionType.Edit;  
            }
            else
            {
                note.Class = clazzObject;
                note.ClassID = clazzObject.ID;
                note.ClassTypeID = (short)CmsObjectType.ContentNote;
                note.Author = IGlobalistMembership.GetUser().ID;
                note.CreatedDate = DateTime.Now;
                note.ActionType = ActionType.Add;
            }

            note.Name = ViewState["Quote_Name"].ToString();
            string description =Filter(ViewState["Quote_Description"].ToString());
            description = description.Replace("[Quote]", "<div class='SaveReply'>");
            description=description.Replace("[/Quote]", "</div>");
            note.Description = description;

            note.Data = "";//Request("Data");            

            if (id > 0)
            {
                ContentNodeController.UpdateContentNote(note);
            }
            else
            {
                IContent content =new IGlobalist.Cms.Model.Content();
                content = ContentController.GetContent(contentId);
                ContentNoteList list = new ContentNoteList();
                list = content.NoteList;
                note.ActionType = ActionType.Add;
                list.Add(note);
                ContentController.UpdateContent(content);

            }
        }

        private void DeleteThread(long forumId, long id)
        {
            CategoryController.DeleteCategory(id);

            //delete theard in page
            IPage forum = PageController.GetPage(forumId);
            ContentCategoryList listTheard = new ContentCategoryList();
            listTheard = forum.CategoryList;
            foreach (Category c  in listTheard)
            {
                if (c.ID == id)
                    listTheard.Remove(c);
            }
            forum.CategoryList = listTheard;
            PageController.UpdatePage(forum);
        }

        private void  Permissions_Forum(long id)
        {
            IContentCategory c = CategoryController.GetCategory(id);
            c.Version = Convert.ToInt16(ViewState["Version"].ToString()); ;
            CategoryController.UpdateCategory(c);
            
        }


        private void DeleteTopic(long id)
        {
            CategoryController.DeleteCategory(id);
        }

        private void DeleteContent(long id)
        {
            IContent content = ContentController.GetContent(id);
            ContentNoteList list = new ContentNoteList();
            list = content.NoteList;
            foreach (ContentNote n in list)
            {
                if (n.ParentID == id)
                {
                    ContentNodeController.DeleteContentNote(n.ID);                    
                }
            }
            ContentController.DeleteContent(id);
        }

        private void DeleteReply(long id)
        {
           //del note in content
            if (id > 0)
            {
                IContent content = ContentController.GetContent(id);
                ContentNoteList list = new ContentNoteList();
                list = content.NoteList;
                foreach (ContentNote n in list)
                {
                    //if (n.ID == id)
                        list.Remove(n);
                    //break;
                }
                content.NoteList = list;
                ContentController.UpdateContent(content);

                //delete note
                ContentNodeController.DeleteContentNote(id);
            }
        }

        private void DeleteForum(long id)
        {
            PageController.DeletePage(id);
        }

        private void UploadContentfile(IContent content, long id)
        {
            content.ID = id;
            Regex linkPage = new Regex(@"\[(.*)\]");
            ArrayList listfile = new ArrayList();
            String scontent = (String)content.Content;
            string link = "";
             foreach (Match field in linkPage.Matches(scontent))
            {
                 
                if (field.Success == true)
                {
                    string fileName = field.Groups[1].Value;

                    //if (fileName.IndexOf("attachment=")!= 0)
                    fileName = fileName.Replace("attachment=", "");
                    listfile.Add(new ListItem(fileName, fileName));
                    string ext = fileName.Substring(fileName.IndexOf("."), fileName.Length - fileName.IndexOf(".")).ToUpper();
                    if ((ext == ".JPG") || (ext == ".GIF") || (ext == ".PNG"))
                    {
                        link = "<a href='#' onclick=JsExp.openImage('/" + IGlobalistMembership.GetUser().ID + "/" + id + "/" + fileName + "') ><img  border='0' valign='middle' src='../ImageView.aspx?mdim=120&forum=/" + IGlobalistMembership.GetUser().ID + "/" + id + "/" + fileName + "'></a>";
                        
                    }
                    else
                    {
                        link =  "Attach file:" + "<a href='../CmsData/Forum/" + IGlobalistMembership.GetUser().ID + "/" + id + "/"+ fileName+ "'>" + fileName + "</a>";
                    }
                    scontent = scontent.Replace(field.Groups[0].Value, link);
                }
                 
            }
            content.Description = scontent;
            content.Content = scontent;

            ContentController.UpdateContent(content);

           //savefile
            string path = HttpContext.Current.Server.MapPath(FolderForumVirtualPath + "/" + IGlobalistMembership.GetUser().ID);
            string p = HttpContext.Current.Server.MapPath(FolderForumVirtualPath + "/" + IGlobalistMembership.GetUser().ID+"/" + id);

            if (!System.IO.Directory.Exists(p))
                System.IO.Directory.CreateDirectory(p);

            foreach(ListItem l in listfile)
            {
                FileInfo f= new FileInfo(Path.Combine(path, l.Value));

                f.CopyTo(Path.Combine(p, l.Value), true);
                //f.MoveTo(Path.Combine(p, l.Value));
                
            }

        }

        private string Filter(string content)
        {
            string contentFilter = content;
            contentFilter.Replace("<script>", "");
            contentFilter.Replace("</script>", "");
           return contentFilter;
        }
    }
}
